package controller.day04;

import entity.User;
import service.UserService;
import service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "UpdateUserServlet", value = "/UpdateUserServlet")
public class UpdateUserServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 将请求与响应的字符编码设置为 UTF-8
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //1. 接收页面用户数据
        String idStr =  request.getParameter("userId");
        Integer id = Integer.valueOf(idStr);
        String username =  request.getParameter("username");
        String password =  request.getParameter("password");
        String powerStr =  request.getParameter("power");
        Integer power = Integer.valueOf(powerStr);

        //2. 封装成User对象
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setPassword(password);
        user.setPower(power);

        //3. service  修改用户数据
        boolean result =  userService.updateUser(user);

        //4. 数据绑定  //5. 页面跳转
        if(result){
            request.setAttribute("msg","修改用户信息成功");
            request.getRequestDispatcher("/day04/success.jsp").forward(request,response);
        }else{
            request.setAttribute("msg","修改用户信息失败");
            request.getRequestDispatcher("/day04/update.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
